﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using SBPweb.Modules.Smartparts;
using SBPweb.Modules.Modularity;

using SBPweb.MediaCenter.Tools.WF;

using MSNPSharp;

namespace SBPweb.MediaCenter.Modules.Messenger.MSN.WF
{
    public partial class MessengerControl : UserControl, ISmartpart
    {
        #region Private members

        private MSNPSharp.Messenger pMessenger;
        private Conversation mConversation;

        private bool pIsModal;
        private Aligning pAlign;
        private IModule pParentModule;

        public delegate void BoolParameteredHandler(bool value);
        public delegate void StringParameteredHandler(string value);

        #endregion

        #region Contructor logic

        public MessengerControl(IModule parentModule)
        {
            pParentModule = parentModule; 
            
            InitializeComponent();

            InitializeMessengerComponents();

            Align = Aligning.Fill;
        }

        private void InitializeMessengerComponents()
        {
            Messenger = new MSNPSharp.Messenger();

            Messenger.Nameserver.SignedIn += new EventHandler(Nameserver_SignedIn);
            Messenger.Owner.StatusChanged += new Contact.StatusChangedEventHandler(Owner_StatusChanged);
            Messenger.Owner.DisplayImage = new DisplayImage();
            Messenger.Owner.DisplayImage.Image = this.tsbOwnAvatar.Image;
        }

        #endregion

        #region Public members

        public delegate void ParameterlessHandler();
        public delegate void TextMessageHandler(TextMessageEventArgs textMessage);
        public delegate void ContactHandler(ContactEventArgs contactEventArg);

        public MSNPSharp.Messenger Messenger
        {
            get { return pMessenger; }
            set { pMessenger = value; }
        }

        #endregion

        #region Property accessors

        public Conversation Conversation
        {
            get
            {
                return mConversation;
            }
            set
            {
                mConversation = value;
            }
        }
        
        public Aligning Align
        {
            get
            {
                return pAlign;
            }
            set
            {
                pAlign = value;
                Dock = AligningConverter.AligningToDockStyle(value);
            }
        }

        public IModule ParentModule
        {
            get
            {
                return pParentModule;
            }
        }

        public bool IsVisible
        {
            get
            {
                return base.Visible;
            }
            set
            {
                base.Visible = value;
            }
        }

        public bool IsEnabled
        {
            get
            {
                return base.Enabled;
            }
            set
            {
                base.Enabled = value;
            }
        }

        public bool IsModal
        {
            get
            {
                return pIsModal;
            }
        }

        #endregion

        #region Private Helper Methods

        private void SetStatusLabel()
        {
            if (InvokeRequired)
            {
                this.Invoke(new ParameterlessHandler(SetStatusLabel));
                return;
            }

            switch (Messenger.Owner.Status)
            {
                case PresenceStatus.Away:
                    this.tssbStatus.Text = "Away";
                    break;
                case PresenceStatus.BRB:
                    this.tssbStatus.Text = "Be right back";
                    break;
                case PresenceStatus.Busy:
                    this.tssbStatus.Text = "Busy";
                    break;
                case PresenceStatus.Hidden:
                    this.tssbStatus.Text = "Hidden";
                    break;
                case PresenceStatus.Idle:
                    this.tssbStatus.Text = "Idle";
                    break;
                case PresenceStatus.Lunch:
                    this.tssbStatus.Text = "Out to lunch";
                    break;
                case PresenceStatus.Offline:
                    this.tssbStatus.Text = "Offline";
                    break;
                case PresenceStatus.Online:
                    this.tssbStatus.Text = "Online";
                    break;
                case PresenceStatus.Phone:
                    this.tssbStatus.Text = "In a call";
                    break;
                case PresenceStatus.Unknown:
                    this.tssbStatus.Text = "Unknown";
                    break;
                default:
                    break;
            }
        }

        private void RemoveNameFromTheJoinedContactsList(ContactEventArgs e)
        {
            //if (InvokeRequired)
            //{
            //    this.Invoke(new ContactHandler(this.RemoveNameFromTheJoinedContactsList), e);
            //    return;
            //}

            //this.lwContacts.Items[e.Contact.Name].ForeColor = Color.Black;
        }

        private void AddNameToTheJoinedContactsList(ContactEventArgs e)
        {
            //if (InvokeRequired)
            //{
            //    this.Invoke(new ContactHandler(this.AddNameToTheJoinedContactsList), e);
            //    return;
            //}

            //foreach (ListViewItem item in lwContacts.Items)
            //{
            //    if (item.Text.Split('-')[0].Trim() == e.Contact.Name)
            //    {
            //        this.lwContacts.Items[this.lwContacts.Items.IndexOf(item)].ForeColor = Color.Green;
            //        break;
            //    }
            //}
        }

        private void AddTextMessageToTheHistory(TextMessageEventArgs e)
        {
            //if (InvokeRequired)
            //{
            //    this.Invoke(new TextMessageHandler(this.AddTextMessageToTheHistory), e);
            //    return;
            //}

            //this.rtbMessageHistory.AppendText(string.Format("{0} says: {1}\n\n", e.Sender.Name, e.Message.Text));
        }

        private void FillContactList()
        {
            //if (InvokeRequired)
            //{
            //    this.Invoke(new ParameterlessHandler(FillContactList));
            //    return;
            //}
            //this.lwContacts.Items.Clear();

            //ContactList contacts = Messenger.Nameserver.ContactList;

            //foreach (Contact contact in contacts.All)
            //{
            //    this.lwContacts.Items.Add(String.Format("{0} - {1}", contact.Name, contact.Status));
            //}
        }

        private void SetPersonalSettingsButtonEnableState(bool enabled)
        {
            if (InvokeRequired)
            {
                this.Invoke(new BoolParameteredHandler(this.SetPersonalSettingsButtonEnableState), enabled);
                return;
            }

            this.setPersonalSettingsToolStripMenuItem.Enabled = enabled;
        }

        private Contact GetSelectedContact()
        {
            Contact selectedContact = null;
            //string selectedContactName = string.Empty;

            //if (this.lwContacts.SelectedItems[0] != null)
            //{
            //    selectedContactName = this.lwContacts.SelectedItems[0].Text.ToString().Split('-')[0].Trim();
            //}

            //ContactList contacts = Messenger.Nameserver.ContactList;

            //foreach (Contact contact in contacts.All)
            //{
            //    if (contact.Name == selectedContactName)
            //    {
            //        selectedContact = contact;
            //        break;
            //    }
            //}

            return selectedContact;
        }

        private void SetPersonalMessage(string newPersonalMessage)
        {
            if (InvokeRequired)
            {
                this.Invoke(new StringParameteredHandler(this.SetPersonalMessage), newPersonalMessage);
                return;
            }

            this.tstbPersonalMessage.Text = newPersonalMessage;
        }

        #endregion

        #region Event Handlers

        private void tsmiSignIn_Click(object sender, EventArgs e)
        {
            SignInForm sif = new SignInForm(this.Messenger);
            sif.ShowDialog();
        }

        void Owner_StatusChanged(object sender, StatusChangeEventArgs e)
        {
            SetStatusLabel();
        }

        void Nameserver_SignedIn(object sender, EventArgs e)
        {
            this.SetPersonalSettingsButtonEnableState(true);
            SetStatusLabel();
            
            Messenger.Owner.Status = PresenceStatus.Online;

            Conversation = Messenger.CreateConversation();
            Conversation.Switchboard.TextMessageReceived += new TextMessageReceivedEventHandler(Switchboard_TextMessageReceived);
            Conversation.Switchboard.ContactJoined += new ContactChangedEventHandler(Switchboard_ContactJoined);
            Conversation.Switchboard.ContactLeft += new ContactChangedEventHandler(Switchboard_ContactLeft);
            Messenger.Owner.PersonalMessageChanged += new Contact.ContactChangedEventHandler(Owner_PersonalMessageChanged);
        }

        void Owner_PersonalMessageChanged(object sender, EventArgs e)
        {

        }

        void Switchboard_ContactLeft(object sender, ContactEventArgs e)
        {
            RemoveNameFromTheJoinedContactsList(e);
        }

        void Switchboard_ContactJoined(object sender, ContactEventArgs e)
        {
            AddNameToTheJoinedContactsList(e);
        }

        void Switchboard_TextMessageReceived(object sender, TextMessageEventArgs e)
        {
            AddTextMessageToTheHistory(e);
        }

        private void tsbConnect_Click(object sender, EventArgs e)
        {
            SignInForm sif = new SignInForm(this.Messenger);
            sif.ShowDialog();
        }

        private void onLineToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Messenger.Owner.Status = PresenceStatus.Online;
        }

        private void busyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Messenger.Owner.Status = PresenceStatus.Busy;
        }

        private void beRightBackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Messenger.Owner.Status = PresenceStatus.BRB;
        }

        private void awayToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Messenger.Owner.Status = PresenceStatus.Away;
        }

        private void signOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Messenger.Disconnect();
        }

        private void tsbOwnAvatar_Click(object sender, EventArgs e)
        {
            OpenFileDialog od = new OpenFileDialog();
            od.DefaultExt = "jpg";
            od.Filter = "Picture files (*.jpg)|*.jpg";
            DialogResult dr = od.ShowDialog();

            if (dr == DialogResult.OK)
            {
                this.tsbOwnAvatar.Image = System.Drawing.Image.FromFile(od.FileName);
                DisplayImage di = new DisplayImage();
                di.Image = this.tsbOwnAvatar.Image;
                Messenger.Owner.DisplayImage = di;
            }
        }

        private void tsbRefreshContacts_Click(object sender, EventArgs e)
        {
            FillContactList();
        }

        private void btnSendMessage_Click(object sender, EventArgs e)
        {
            //if (Conversation.SwitchboardProcessor == null || Conversation.SwitchboardProcessor.Connected == false)
            //{
            //    Conversation.Messenger.Nameserver.RequestSwitchboard(Conversation.Switchboard, this);
            //}

            //Conversation.Switchboard.SendTextMessage(new TextMessage(this.rtbMessageWriter.Text));
            //this.rtbMessageHistory.AppendText(string.Format("{0} says: {1}\n\n", Messenger.Owner.Name, this.rtbMessageWriter.Text));
            //this.rtbMessageWriter.Clear();
            //this.rtbMessageWriter.ResetText();
        }

        private void rtbMessageWriter_TextChanged(object sender, EventArgs e)
        {
            //if (rtbMessageWriter.Text == string.Empty)
            //{
            //    this.btnSendMessage.Enabled = false;
            //}
            //else
            //{
            //    this.btnSendMessage.Enabled = true;
            //}
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //if (Conversation.Switchboard == null || Conversation.SwitchboardProcessor == null)
            //{
            //    Conversation.Messenger.Nameserver.RequestSwitchboard(Conversation.Switchboard, this);
            //}

            //string selectedContact = string.Empty;

            //if (this.lwContacts.SelectedItems[0] != null)
            //{
            //    selectedContact = this.lwContacts.SelectedItems[0].Text.ToString().Split('-')[0].Trim();
            //}

            //ContactList contacts = Messenger.Nameserver.ContactList;

            //foreach (Contact contact in contacts.All)
            //{
            //    if (contact.Name == selectedContact)
            //    {
            //        if (!Conversation.Switchboard.Contacts.Contains(contact.Mail))
            //        {
            //            Conversation.Switchboard.Invite(contact.Mail);
            //        }
            //        break;
            //    }
            //}
        }

        private void tsbSendFile_Click(object sender, EventArgs e)
        {
            //string selectedContact = string.Empty;

            //if (this.lwContacts.SelectedItems[0] != null)
            //{
            //    selectedContact = this.lwContacts.SelectedItems[0].Text.ToString().Split('-')[0].Trim();
            //}

            //OpenFileDialog od = new OpenFileDialog();

            //DialogResult dr = od.ShowDialog();

            //if (dr == DialogResult.OK)
            //{
            //    MSNSLPHandler msnslpHandler = Messenger.GetMSNSLPHandler(GetSelectedContact().Mail);
            //    msnslpHandler.LocalEndPoint = (System.Net.IPEndPoint)Messenger.NameserverProcessor.LocalEndPoint;
            //    FileStream fileStream = new FileStream(od.FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            //    P2PTransferSession session = msnslpHandler.SendInvitation(Messenger.Owner.Mail, GetSelectedContact().Mail, Messenger.Owner.DisplayImage);
            //    session.AutoCloseStream = true;
            //    session = msnslpHandler.SendInvitation(Messenger.Owner.Mail, GetSelectedContact().Mail, Path.GetFileName(od.FileName), fileStream);
            //}

        }

        #endregion

        private void setPersonalSettingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Personal personal = new Personal(Messenger);
            personal.ShowDialog();
        }

        private void setPersonalSettingsToolStripMenuItem_EnabledChanged(object sender, EventArgs e)
        {
            if (this.setPersonalSettingsToolStripMenuItem.Enabled)
            {
                this.setPersonalSettingsToolStripMenuItem.ToolTipText = Resources.MessengerResources_en_US_resx.MessengerCtrl_SetStatusButtonToolStripIfEnabled;
            }
            else
            {
                this.setPersonalSettingsToolStripMenuItem.ToolTipText = Resources.MessengerResources_en_US_resx.MessengerCtrl_SetStatusButtonToolStripIfNotEnabled;
            }
        }
    }
}
